package com.study.zzedu.ui.classchat;

import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.study.zzedu.R;
import com.study.zzedu.adapter.MsgAdapter;
import com.study.zzedu.base.BaseMvpActivity;
import com.study.zzedu.entity.Msg;
import com.study.zzedu.ui.login.LoginActivity;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.LogUtil;
import com.study.zzedu.utils.ToastUtil;
import com.study.zzedu.widget.InfoDialog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ClassChatActivity extends BaseMvpActivity<ChatContract.IView,ClassChatPresenter> implements  ChatContract.IView,View.OnClickListener {
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mRefreshLayout;
    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Button left_Button;
    private Button right_button;
    private EditText mEditText;
    private MsgAdapter msgAdapter;
    private List<Msg> dataList = new ArrayList<Msg>();
    private final Timer timer = new Timer();
    private TimerTask task;
    private int msgType;

    //false:请求老数据 true :新数据
    private boolean dataFlag = true;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            // 请求新数据
            if(dataList.size()>0){
                getRequestData("2","false",dataList.get(dataList.size()-1).getTime());
            }
            super.handleMessage(msg);
        }
    };
    @Override
    protected int getLayoutID() {
        return R.layout.activity_class_chat;
    }

    @Override
    protected ClassChatPresenter createPresenter() {
        return new ClassChatPresenter();
    }

    @Override
    protected ChatContract.IView createView() {
        return this;
    }

    private RelativeLayout btnBack;
    @Override
    protected void initView() {
        btnBack = findViewById(R.id.rl_back);
        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_msg);
        LinearLayoutManager lm = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(lm);
        msgAdapter = new MsgAdapter(dataList);
        //mRecyclerView.addItemDecoration(new SpacesItemDecoration(30));
        mRecyclerView.setAdapter(msgAdapter);

        left_Button = (Button) findViewById(R.id.left_button);
        right_button = (Button) findViewById(R.id.right_button);
        mEditText = (EditText) findViewById(R.id.edit_view);
    }

    @Override
    protected void initData() {
        Date date = new Date();
        //初次请求，请求基准时间之前数据
        dataFlag = false;
        getRequestData("1","false",df.format(date).toString());
        //getRequestData("2","false","2020-09-04 13:02:59");
        task = new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Message message = new Message();
                message.what = 1;
                //如果正在请求老数据，就暂停刷新新数据
                if(dataFlag){
                    handler.sendMessage(message);
                }
            }
        };
        timer.schedule(task,6000,6000);
    }

    @Override
    protected void initListener() {
        left_Button.setOnClickListener(this);
        right_button.setOnClickListener(this);
        mEditText.setOnClickListener(this);

        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Toast.makeText(ClassChatActivity.this, "拉了一下", Toast.LENGTH_SHORT).show();
                if(dataList.size()>0){
                    dataFlag = false;
                    getRequestData("1","false",dataList.get(0).getTime());
                }

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRefreshLayout.setRefreshing(false);
                    }
                },1300);
            }
        });
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String content = mEditText.getText().toString();
        switch (v.getId()) {
            case R.id.left_button:
                break;
            case R.id.right_button:
                if (TextUtils.isEmpty(mEditText.getText().toString())) {
                    ToastUtil.showShortToast("发送的消息不能为空！");
                    return;
                }
                getPresenter().sendData(ClassChatActivity.this,mEditText.getText().toString());
                mEditText.setText("");


                Message message = new Message();
                message.what = 1;
                //如果正在请求老数据，就暂停刷新新数据
                if(dataFlag){
                    handler.sendMessage(message);
                }
                break;
        }
    }

    @Override
    public void getSendBack(String name) {
        ToastUtil.showShortToast("getSendBack");
    }

    @Override
    public void getData(String data) {

        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray jArray = jObject.getJSONArray("data");
            if(jArray.length()>0){
                for (int i=0;i<jArray.length();i++){
                    JSONObject job = jArray.getJSONObject(i);
                    msgType = job.getString("sno").equals(AppConstant.userCode) ? Msg.TYPE_SENT : Msg.TYPE_RECEIVED;

                    if(dataFlag){
                        dataList.add(new Msg(job.getString("content"),msgType,job.getString("speakerName"),job.getString("pubdate")));
                    }else {
                        dataList.add(0,new Msg(job.getString("content"),msgType,job.getString("speakerName"),job.getString("pubdate")));
                    }
                }
                msgAdapter.notifyDataSetChanged();
                if(dataFlag){
                    mRecyclerView.smoothScrollToPosition(msgAdapter.getItemCount()-1);
                }
            }
            if(!dataFlag){
                dataFlag = true;
            }
        } catch (Exception e) {
            e.toString();
        }

    }

    @Override
    public void showError(String error) {
        if (null != error && !TextUtils.isEmpty(error)) {
            ToastUtil.showShortToast(error);
        }
    }

    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }

    //beforeOrAfter 1 (老数据)  2 （新数据）
    private void getRequestData(String beforeOrAfter,String onlyTeacher,String timeStirng){
        String d = beforeOrAfter.equals("1")?"前请求":"后请求";
        LogUtil.e("data","请求基准时间："+timeStirng+" "+d);
        getPresenter().getChatInfoList(ClassChatActivity.this,beforeOrAfter,onlyTeacher,timeStirng);
    }

}